<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>数据库管理</title>
    <link rel="stylesheet" href="/static/css/bootstrap.css">
    <script src="/static/js/jquery.js"></script>
    <script src="/static/js/vue.js"></script>
  </head>
  <body>
    <div id="app">

      <nav class="navbar navbar-default">
        <div class="container-fluid">
          <!-- Brand and toggle get grouped for better mobile display -->
          <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="/">数据库管理</a>
          </div>

          <!-- Collect the nav links, forms, and other content for toggling -->
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
              <li class="active"><a href="/conn/index">连接 <span class="sr-only">(current)</span></a></li>
              <li><a href="/dto/index">Dtos</a></li>
              <li><a href="/dataset/index">训练数据集</a></li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
              <li><a href="#">登录</a></li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">系统菜单 <span class="caret"></span></a>
                <ul class="dropdown-menu">
                  <li><a href="#">Action</a></li>
                  <li><a href="#">Another action</a></li>
                  <li><a href="#">Something else here</a></li>
                  <li role="separator" class="divider"></li>
                  <li><a href="#">Separated link</a></li>
                </ul>
              </li>
            </ul>
          </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
      </nav>
      <div class="row" style="padding-bottom: 10px;">
        <div class="col-xs-12 col-md-8">
          <button type="button" class="btn btn-success" @click="handleCreate">新增</button>
        </div>
      </div>

      <table class="table table-bordered">
        <thead>
          <tr>
            <th>序号</th>
            <th>提供商</th>
            <th>名称</th>
            <th>主机</th>
            <th>端口</th>
            <th>账号</th>
            <th>密码</th>
            <th>默认数据库</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item,index) in list" :key="index">
            <td>[[ index + 1 ]]</td>
            <td>[[ item.dbtype ]]</td>
            <td>[[ item.name ]]</td>
            <td>[[ item.host ]]</td>
            <td>[[ item.port ]]</td>
            <td>[[ item.user ]]</td>
            <td>[[ item.passwd ]]</td>
            <td>[[ item.dbname ]]</td>
            <td style="width:200px">
              <button type="button" class="btn btn-primary" @click="handleEdit(item)">编辑</button>
              <button type="button" class="btn btn-danger" @click="handleRemove(  item.id )">移除</button>
            </td>
          </tr>
        </tbody>
      </table>
      <div class="modal fade" tabindex="-1" role="dialog" id="formModal">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 class="modal-title">新增连接</h4>
            </div>
            <div class="modal-body">
              <form class="form-horizontal">
                <div class="form-group">
                  <label for="dbtype" class="col-sm-2">提供商：</label>
                  <div class="col-sm-10">
                    <select class="form-control" v-model="model.dbtype" @change="handleSelect">
                      <option :value="item.label" v-for="(item,index) in listDbs" :key="index">[[ item.label ]]</option>
                    </select>
                  </div>
                </div>
                <div class="form-group">
                  <label for="linkName" class="col-sm-2">名称：</label>
                  <div class="col-sm-10">
                    <input type="text" class="form-control" v-model="model.name" id=" linkName" placeholder="输入连接名称">
                  </div>
                </div>
                <div class="form-group">
                  <label for="host" class="col-sm-2"> [[ model.dbtype =='SQLite'?'文件：': '主机名：']] </label>
                  <div class="col-sm-10">
                    <input type="text" class="form-control" v-model="model.host" id="host" placeholder="输入主机名">
                  </div>
                </div>
                <div class="form-group">
                  <label for="order_num" class="col-sm-2">排序：</label>
                  <div class="col-sm-10">
                    <input type="number" class="form-control" v-model="model.orderNum" id="order_num" placeholder="输入排序">
                  </div>
                </div>
                <div class="form-group" v-if="model.dbtype!='SQLite'">
                  <label for="port" class="col-sm-2">端口：</label>
                  <div class="col-sm-10">
                    <input type="number" class="form-control" v-model="model.port" id="port" placeholder="输入端口">
                  </div>
                </div>
                <div class="form-group" v-if="model.dbtype!='SQLite'">
                  <label for="username" class="col-sm-2">用户名：</label>
                  <div class="col-sm-10">
                    <input type="text" class="form-control" v-model="model.user" id="username" placeholder="输入用户名">
                  </div>
                </div>
                <div class="form-group" v-if="model.dbtype!='SQLite'">
                  <label for="Password" class="col-sm-2">密码：</label>
                  <div class="col-sm-10">
                    <input type="text" class="form-control" v-model="model.passwd" id="Password" placeholder="输入密码">
                  </div>
                </div>
                <div class="form-group" v-if="model.dbtype!='SQLite'">
                  <label for="dbname" class="col-sm-2">默认库：</label>
                  <div class="col-sm-10">
                    <div class="input-group">
                      <input type="text" class="form-control" v-model="model.dbname" placeholder="输入默认数据库">
                      <span class="input-group-addon" id="dbname" @click="fetchDatabase" style="cursor: pointer;">刷新</span>
                    </div>
                  </div>
                </div>
                <div class="form-group" v-if="model.dbtype!='SQLite'">
                  <label for="dbname" class="col-sm-2">可选库：</label>
                  <div class="col-sm-10 box-dbs">
                    <template v-for="(item,index) in listFormDbs">
                      <div class="radio" :key="index">
                        <label> <input type="radio" name="dbname" v-model="model.dbname" @change="handleDbCheck(item)"> [[ item.name ]]</label>
                      </div>
                    </template>
                  </div>
                </div>
              </form>

            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
              <button type="button" class="btn btn-primary" @click="saveChanges(this)">保存</button>
            </div>
          </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
      </div><!-- /.modal -->

    </div>

    <script src="/static/js/bootstrap.js"></script>
    <script>
      new Vue({
        el: '#app',
        delimiters: ["[[", "]]"],
        data() {
          let host = '127.0.0.1'
          return {
            listDbs: [
              { label: 'PGSQL', value: 10000, def_val: { host, port: 5432, orderNum: 100, user: 'postgres', dbname: 'postgres' } },
              { label: 'MSSQL', value: 20000, def_val: { host, port: 1433, orderNum: 200, user: 'sa', dbname: 'master' } },
              { label: 'MYSQL', value: 30000, def_val: { host, port: 3306, orderNum: 300, user: 'root', dbname: 'mysql' } },
              { label: 'SQLite', value: 40000, def_val: { host: '', port: '', orderNum: 400, user: '', dbname: '' } }
            ],
            list: [],
            listFormDbs: [],
            model: {
              id: '',
              name: '',
              dbtype: '',
              orderNum: '',
              host: '',
              port: '',
              user: '',
              passwd: '',
              dbname: '',
            }
          }
        },
        created() {
          this.fetchData()
        },
        methods: {
          fetchData() {
            fetch('/conn/list').then(async response => {
              let data = await response.json()
              this.list = data
              // console.log(data)
            })

          },
          fetchDatabase() {
            // console.log( this.model )
            fetch('/conn/databses', {
              method: "POST",
              headers: {
                "content-type": "application/json"
              },
              body: JSON.stringify(this.model)
            }).then(async response => {
              let data = await response.json()
              if (Array.isArray(data)) {
                this.listFormDbs = data
                return
              }
              // console.log( data )
            })
          },
          handleDbCheck(obj) {
            this.model.dbname = obj.name
            // console.log( obj )
          },
          handleEdit(row) {
            this.model = { ...row }
            $('#formModal').modal('show')
          },
          handleCreate() {
            this.model.id = ''
            $('#formModal').modal('show')
          },
          handleSelect(obj) {
            let dbtype = this.model.dbtype
            let id = this.model.id
            let model = this.listDbs.find(t => t.label == dbtype)
            if (model) {
              this.model = { ...model.def_val, dbtype }
            }
            this.model.id = id
            this.model.name = this.model.dbtype
            // console.log(this.model.dbtype)
          },
          saveChanges() {
            if (this.model.id) {
              this.saveModify(this.model)
            } else {
              this.saveCreate(this.model)
            }
          },
          saveCreate(data) {
            fetch('/conn/create', {
              method: "POST",
              headers: {
                "Content-Type": "application/json"
              },
              body: JSON.stringify(data)
            }).then(async response => {
              this.fetchData()
              let data = await response.json()
              $('#formModal').modal('hide')
            })
          },
          saveModify(data) {
            fetch('/conn/update', {
              method: "PUT",
              headers: {
                "Content-Type": "application/json"
              },
              body: JSON.stringify(data)
            }).then(async response => {
              let data = await response.json()
              this.fetchData()
              $('#formModal').modal('hide')
            })
          },

          handleRemove(id) {
            if (!confirm("确认删除？")) {
              return
            }
            fetch('/conn/delete', {
              method: "POST",
              headers: {
                "Content-Type": "application/json"
              },
              body: JSON.stringify({ id })
            }).then(async response => {
              let data = await response.json()
              this.fetchData()
            })
          }
        }
      })
    </script>

  </body>
</html>